<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力会务会议发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  All rights reserved.
// +----------------------------------------------------------------------
// | 沃德会务会议系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.maiwd.cn
// +----------------------------------------------------------------------
namespace app\api\controller\wddj;

use addons\wddj\library\Wxapp;
use app\api\model\wddj\UserWechat;
use app\common\controller\Api;
use app\common\model\User;
use think\Db;

/**
 * Class AppletUserWechat
 * Desc  小程序微信用户注册登录
 * Create on 2024/3/7 10:03
 * Create by wangyafang
 */
class AppletUserWechat extends Api
{
    protected $noNeedLogin = ['is_register', 'get_phone', 'register', 'login'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

        $configObj = (new \app\admin\model\wddj\Config())->where('id', 1)->find();
        if (empty($configObj['applet_appid'])) {
            $this->error('小程序AppID未配置');
        }
        if (empty($configObj['applet_secret'])) {
            $this->error('小程序AppSecret未配置');
        }
    }

    /**
     * Desc  微信小程序是否注册
     * Create on 2024/3/7 10:05
     * Create by wangyafang
     */
    public function is_register()
    {
        if (!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $code = $this->request->param('code');
        if (empty($code)) {
            $this->error('code参数错误');
        }
        $data = Wxapp::wxlogin($code);
        if (empty($data['openid'])) {
            $this->error('小程序登录失败', $data);
        }
        $openid = $data['openid'];
        $userWechatObj = (new UserWechat())->where('openid', $openid)->find();

        $auth_status = !empty($userWechatObj) ? 1 : 0;
        $this->success('请求成功！', ['auth_status' => $auth_status]);
    }

    /**
     * Desc  微信小程序注册
     * Create on 2024/3/7 10:06
     * Create by wangyafang
     */
    public function register()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $code = $this->request->post('code');
        $disId = $this->request->param('disId');
        $param = $this->request->post();

        if (empty($code)) {
            $this->error('code参数错误');
        }
        $data = Wxapp::wxlogin($code);
        if (empty($data['openid'])) {
            $this->error('小程序注册失败', $data);
        }
        $openid = $data['openid'];
        $avatar = '/assets/addons/wddj/img/user.png';

        $mobile = $param['mobile'];
        $param['nickname'] = substr_replace($mobile, '****', 3, -3);
        Db::startTrans();
        try {
            $user = User::create(array(
                'group_id' => 1,
                'status' => 'normal',
                'joinip' => request()->ip(),
                'jointime' => time(),
                'nickname' => $param['nickname'],
                'avatar' => $avatar,
                'mobile' => $mobile,
                'disId' =>  $disId
            ), true);
            UserWechat::create(array(
                'user_id' => $user->id,
                'openid' => $openid,
                'nickname' => $param['nickname'],
                'avatar' => $avatar,
                'mobile' => $mobile,
                'disId' =>  $disId
            ));
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->auth->direct($user->id);
        $userObj = $this->auth->getUserinfo();
        $userObj['avatar'] = wddj_full_url($userObj['avatar']);
        $this->success('请求成功', $userObj);
    }

    /**
     * Desc  微信小程序登录
     * Create on 2024/3/7 10:06
     * Create by wangyafang
     */
    public function login()
    {
        if (!$this->request->isPost()) {
            $this->error('请求类型错误');
        }

        $code = $this->request->param('code');
        $disId = $this->request->param('disId');
        if (empty($code)) {
            $this->error('code参数错误');
        }
        $data = Wxapp::wxlogin($code);
        if (empty($data['openid'])) {
            $this->error('小程序登录失败', $data);
        }
        $openid = $data['openid'];
        $userWechatObj = (new UserWechat())->where('openid', $openid)->find();
        $userObj = User::get($userWechatObj['user_id']);
        if (!$userObj) {
            $userInfo = array(
                'group_id' => 1,
                'status' => 'normal',
                'joinip' => request()->ip(),
                'jointime' => time(),
                'avatar' => $userWechatObj['avatar'],
                'nickname' => $userWechatObj['nickname'],
                'mobile' => $userWechatObj['mobile'],
            );
            if($disId)
            {
                $userInfo['disId'] = $disId;
                $userWechatObj->disId = $disId;
            }
            $userObj = User::create($userInfo, true);
            $userWechatObj->user_id = $userObj->id;
            $userWechatObj->save();
        }

        $this->auth->direct($userObj->id);
        $userObj = $this->auth->getUserinfo();
        $userObj['avatar'] = wddj_full_url($userObj['avatar']);
        $this->success('请求成功', $userObj);
    }

    /**
     * Desc  获取微信小程序用户手机号
     * Create on 2024/3/7 11:16
     * Create by wangyafang
     */
    public function get_phone()
    {
        if (!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $code = $this->request->get('code');
        $iv = $this->request->get('iv');
        $encryptedData = $this->request->get('encryptedData', '', 'trim');
        if (empty($code)) {
            $this->error('code 参数错误');
        }
        if (empty($iv)) {
            $this->error('iv 参数错误');
        }
        if (empty($encryptedData)) {
            $this->error('encryptedData 参数错误');
        }
        $data = Wxapp::phone($code, $iv, $encryptedData);
        $this->success('请求成功', $data);
    }
}



 